package com.serve.oa.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.serve.oa.entity.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import com.serve.oa.common.lang.Result;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author __tyw
 * @since 2022-10-31
 */
@RestController
@RequestMapping("/role")
public class SysRoleController extends BaseController {

    @GetMapping("/listAll")
    public Result listAll(){
        List<SysRole> data = roleService.list();
        return Result.succ(data);
    }

    @GetMapping("/list")
    @RequiresPermissions("sys:role:list")
    public Result list(String name){

        Page<SysRole> data = roleService.page(getPage(),new QueryWrapper<SysRole>()
                .like(StrUtil.isNotBlank(name), "name", name));


        return Result.succ(data);
    }


    @GetMapping("/menu/{id}")
    @RequiresPermissions("sys:menu:list")
    public Result getMenuById (@PathVariable("id") Long id){

        Assert.notNull(id, "找不到用户");
        List<SysRoleMenu> list =  roleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id",id));
        ArrayList<String> arr = new ArrayList<>();
        for(SysRoleMenu item: list){
            arr.add(item.getMenuId().toString());
        }

        return Result.succ(arr);

    }

    @PostMapping("/menu/{id}")
    @RequiresPermissions("sys:role:perm")
    public Result eidtMenuById (@PathVariable("id") Long id,@RequestBody List<Long> params){

        Assert.notNull(id, "找不到用户");


        List<SysUser> plist =  userService.list(new QueryWrapper<SysUser>().inSql("id","select user_id from sys_user_role where role_id = " + id));

        plist.forEach(i->{
            redisTemplate.delete("perm:"+ i.getUsername());
        });

        roleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id",id));






        List<SysRoleMenu> data = new ArrayList<>();
        params.forEach(i->{
            SysRoleMenu a = new SysRoleMenu();
            a.setRoleId(id);
            a.setMenuId(i);
            data.add(a);

        });
        roleMenuService.saveBatch(data);


        return Result.succ("成功");

    }

}
